/*
 * The MIT License
 *
 * Copyright 2011 Roman Yakovenko <erelus@gmail.com>.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package com.stego.image;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @author Roman Yakovenko <erelus@gmail.com>
 */
public class Image {

    protected File file;
    protected BufferedImage img;

    private static final String IMAGE_FORMAT = "png";

    public Image(File file) {
        this.file = file;
    }

    public void open() throws IOException {
        BufferedImage bufferedImage = null;
        bufferedImage = ImageIO.read(this.file);
        this.img = bufferedImage;
    }

    public Pixel[][] getPixels() throws IOException {
        if (null == this.img) {
            this.open();
        }
        Pixel[][] data = new Pixel[img.getWidth()][img.getHeight()];
        for (int i = 0; i < img.getWidth(); i++) {
            for (int j = 0; j < img.getHeight(); j++) {
                data[i][j] = new Pixel((img.getRGB(i, j)));
            }
        }
        return data;
    }

    public void save() throws IOException {
        ImageIO.write(this.img, IMAGE_FORMAT, this.file);
    }

    public void save(File file) throws IOException {
        ImageIO.write(this.img, IMAGE_FORMAT, file);
    }

    public void setFile(File file) {
        this.file = file;
    }

    public void setPixels(Pixel[][] pixels) {
        int width = pixels.length;
        int height = pixels[0].length;
        BufferedImage bufferedImage = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_ARGB);
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                bufferedImage.setRGB(i, j, pixels[i][j].getPixel());
            }
        }
        this.img = bufferedImage;
    }
}
